"use strict";

var extrasCustomAwayMessageMode = false;

//Add dlc tab features+scroll initialisation to the startup
startupPostPropertyLoadTasks.push(initialiseiChatCustomMessages);

function initialiseiChatCustomMessages()
{
	//We only want to do something if ProhibitExtrasMac is false. This makes things a little long winded, unfortunatly.
	var promise = new Promise(
		function(resolve, reject)
		{
			var promise = hookPropertyToFunction(	"ProhibitExtrasMac",
													"bool",
				function(propertyName, typePattern, propValueArray)
				{
					if(propValueArray[0] !== true)
					{
						var ichatCustomMessagePromise = hookPropertyToFunction(	"iChatAwayMessageCustomMode",
																				"bool",
																				customAwayMessageChange);
						
						ichatCustomMessagePromise = ichatCustomMessagePromise
						.then(
							function()
							{
								$("#extra-iChatAwayCustomMessage").on("keydown", 
									function(e)
									{
										var key = e.keyCode;
										
										if(key === 13) // Enter key
										{
											customAwayMessageComplete();
										}
										else if(key === 27) // Esc key
										{
											//Cancel by setting an empty string
											setPropertyValue("iChatAwayMessageCustom", "string", [""]);
											customAwayMessageComplete();
										}
									});
								
								resolve();
							});
						
						//Resolve/reject with the resolution of ichatCustomMessagePromise
						resolve(ichatCustomMessagePromise);
					}
					else
					{
						//If mac extras are prohibited, we can just immediatly resolve
						resolve();
					}
				});

			//don't get stuck forever if promise fails.
			promise.catch(
				function(e)
				{
					reject(e);
				});
		});
	
	return promise;
}

function customAwayMessageChange(propertyName, typePattern, propValueArray)
{
	if(propValueArray && propValueArray.length > 0)
	{
		var customModeEnabled = propValueArray[0];
		
		if(customModeEnabled)
		{
			$("#extra-iChatAwayCustomMessage").removeClass("noDisplay");
			$($("#extra-iChatAwayMessage").parents(".selectricWrapper")[0]).addClass("noDisplay");
			$("#extra-iChatAwayCustomMessage").focus();
		}
		else
		{
			$("#extra-iChatAwayCustomMessage").addClass("noDisplay");
			$($("#extra-iChatAwayMessage").parents(".selectricWrapper")[0]).removeClass("noDisplay");
		}
	}
	else
		console.error(logStrCpp("propValueArray for iChatAwayMessageCustomMode are empty"));
	
	return true;
}

function customAwayMessageComplete()
{
	setPropertyValue("iChatAwayMessageCustomMode", "bool", [false]);
}